package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"product-mall/models/cache"
	"product-mall/models/mysql"
	"product-mall/productrpc/internal/svc"
	"product-mall/productrpc/productrpc"
	"time"
)

type ListProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProductLogic {
	return &ListProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProductLogic) ListProduct(in *productrpc.ListProductRequest) (*productrpc.ListProductResponse, error) {
	// todo: add your logic here and delete this line

	page := int(in.Page)
	if page <= 0 {
		page = 1
	}

	pageSize := 10
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var product []mysql.Product
	query := mysql.DB.Debug().Offset(offset).Limit(pageSize).Order("price")

	get := cache.Rdb.Get(l.ctx, "productList")
	if get.Val() == "" {
		if in.Title != "" {
			query = query.Where("title like ?", "%"+in.Title+"%")
		}

		query.Find(&product)

		marshal, _ := json.Marshal(product)
		cache.Rdb.Set(l.ctx, "productList", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
	}

	var productList []*productrpc.ListProduct

	for _, m := range product {
		list := productrpc.ListProduct{
			Id:      int64(m.ID),
			Title:   m.Title,
			Price:   float32(m.Price),
			Image:   m.Image,
			ClassId: m.ClassId,
		}
		productList = append(productList, &list)
	}
	return &productrpc.ListProductResponse{List: productList}, nil
}
